define(['zepto', 'utils', 'JST', 'cityPicker'], function($, utils, JST){
  return {
    init: function(_CTX_, temp) {
      this._CTX_ = _CTX_
      this.temp = temp
      this.modal = {}

      this.$regionEdit = $('[href="#region-edit"]')

      this.$regionEdit.length ? this.bindPushAction() : void 0
    },

    bindPushAction: function() {

      var that = this

      // on location edit
      $(document).on('click', '[href="#region-edit"]', function(e) {
        e.preventDefault()
        var defer = that.compileRegionPage()

        $.when(defer).done(function($page) {
                $.push.transitionIn($page)
            })

      })

      // On location edited
      this.$regionEdit.on('edited:profile:region', function(e, $page, country, province, city, district) {

        var itemDomString = $(JST.regionItemTpl({
          'country': country,
          'province': province,
          'city': city,
          'district': district
        }))

        if(that.temp) {
          $.toast("修改我的地区成功");
          setTimeout(function() {
                  window.location.reload()
                 }, 500)
        } else {
          $.push.transitionOut($page, {
            beforeTransition: function() {
              that.$regionEdit.off()
                .parent().empty().html(itemDomString)
              that.$regionEdit.parent().trigger("refresh")
            }
          })
        }
      })
    },

    compileRegionPage: function() {

      var that = this,
        deferPage = $.Deferred(),
        defer = this.requestLocation()

      $.when(defer).done(function(data) {

        that.modal.country = data.countryDisplay

        var prds = data.prdValue.split(",")

        if(prds.length == 3) {
          that.modal.province = prds[0]
                   that.modal.city = prds[1]
                 that.modal.district = prds[2]
               }else {
                 that.modal.province = prds[0]
                   that.modal.city = prds[1]
                 that.modal.district = prds[1]
               }

        var $page = $(JST.regionEditTpl({
          'countryDisplay': data.countryDisplay,
          'countryValue': data.countryValue,
          'prd': data.prd,
          'prdValue': data.prdValue
        }))

        // Store request location
        that.modal.location = data.location

        // Bind submit
        that.bindRegionEditPageEvent($page)

        // Set defer as resolve status
        deferPage.resolve($page)
      })

      return deferPage.promise()
    },

    requestLocation: function() {
      var defer = $.Deferred(),
              url = this._CTX_.root + '/profile/region'

          // Show request indicator
          $.showIndicator()

          // Request for rounds data
          $.ajax({
            'type': 'GET',
            'url': url,
            'cache': false
          }).done(function(response) {
            $.hideIndicator()  // Hide request indicator
            utils.processResult(response, function(result) {
                defer.resolve(result.data)
            }, function(result) {
                $.toast(result.message || '获取我的地区失败')
            })
          })

        return defer.promise()
    },

    bindRegionEditPageEvent: function($page) {
      var that = this,
        $country = $('input[name="country"]', $page),
        $prd = $('input[name="prd"]', $page),
        $countrySelector = $('input[name="countrySelector"]', $page),
        $prdselector = $('input[name="prdSelector"]', $page)

      $countrySelector.picker({
            toolbarTemplate: '<header class="bar bar-nav">\
                                <button class="button button-link pull-right close-picker">确定</button>\
                                <h1 class="title">请选择国家</h1>\
                             </header>',
            cols: [
              {
                textAlign: 'center',
                values: ['CHINA', 'OTHER'],
                displayValues: ['中国', '其他']
              }
            ],
            formatValue: function (picker, value, displayValue){
              $(this.input).next().val(value)

              that.modal.country = displayValue

              if(value == 'OTHER') {
                $(".prd-select").addClass("hide");
              }else {
                $(".prd-select").removeClass("hide");
              }
              return displayValue
            }
          });
        
          $prdselector.cityPicker({
            toolbarTemplate: '<header class="bar bar-nav">\
                                <button class="button button-link pull-right close-picker">确定</button>\
                                <h1 class="title">请选择省市区</h1>\
                             </header>',
           formatValue: function (picker, value, displayValue){
               $(this.input).next().val(value)

               console.log(value)

               if(value[2] != "") {
                 that.modal.province = value[0]
                   that.modal.city = value[1]
                 that.modal.district = value[2]
               } else {
                 that.modal.province = value[0]
                   that.modal.city = value[0]
                 that.modal.district = value[1]
               }

               return value
             }
          });

        $page.on('click', '#submit', function(e) {

          e.preventDefault()
          
          var flag = true;

          var country = $country.val().trim()
          if(country == "") {
        	  flag = false;
        	  $.toast('国家不能为空');
          }

          var prd = $prd.val().trim()
        if(country == 'CHINA' && prd == "") {
        	flag = false;
        	$.toast('省市区不能为空');
        }

          if(flag) {
        	  var submiting = that.submitLocation(country, prd)
              $.when(submiting).done(function(data) {
                that.$regionEdit.trigger('edited:profile:region', [$page, that.modal.country, that.modal.province, that.modal.city, that.modal.district])
              })
          }
          
        })
    },

    submitLocation: function(country, prd) {
      var that = this, defer = $.Deferred()
      $.showIndicator()
      $.post(that._CTX_.root + "/profile/region", {
        'country': country,
        'prd': prd,
        '_method': 'PATCH'
      }).done(function(response) {
        $.hideIndicator()
              utils.processResult(response, function(result) {
                defer.resolve(result.data)
            }, function(result) {
                $.toast(result.message || '修改失败')
                defer.resolve(result.data)
            })
      })
    }
  }
})